package edu.ccut.saturn.studio.authority.part;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.w3c.dom.Node;

import  edu.ccut.saturn.studio.authority.editor.AuthorityEditor;
import  edu.ccut.saturn.studio.authority.model.AuthorityVO;
import  edu.ccut.saturn.studio.authority.model.AuthorityModel;
import  edu.ccut.saturn.studio.authority.model.Resource;
import  edu.ccut.saturn.studio.authority.page.AddResourceDialog;
import  edu.ccut.saturn.studio.authority.page.EditResourceDialog;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnProjectUtil;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnSWTUtils;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnSectionPart;

public class AuthorityPart extends SaturnSectionPart {
	private AuthorityEditor ae;
	private IProject project = null;

	private TableViewer resourcesTableViewer;
	private Table table;
	private AuthorityVO authorityVO;

	AuthorityModel dm;

	public AuthorityPart(Composite parent, IManagedForm form,
			AuthorityEditor ae) {
		super(parent, form);
		this.ae = ae;
		this.dm = ae.getDACDefinition();
		this.authorityVO = dm.getAuthorityVO();
		getSection().setClient(createClient(form));
		
		project = SaturnProjectUtil.getProject(ae.getEditorInput());
//		String projectName = dm.getProjectName();
//		if (projectName != null && !projectName.equals("")) {  //$NON-NLS-1$
//			project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
//		}
	}
	public void dispose() {

	}
	Control createClient(IManagedForm form) {
		AuthorityModel dm = ae.getDACDefinition();

		List<Resource> resources = this.authorityVO.getResources();
		FormToolkit toolkit = form.getToolkit();
		Composite composite = new Composite(getSection(), SWT.NULL);
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 3;
		composite.setLayout(gridLayout);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

		GridData gridDataText1 = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gridDataText1.horizontalSpan = 1;

		GridData gridDataText2 = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gridDataText2.horizontalSpan = 2;


		final Label resourceLabel = new Label(composite, SWT.NONE);
		resourceLabel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false,
				false));
		resourceLabel.setText(Messages.getString("AuthorityFilePropertiesPart.source"));  //$NON-NLS-1$

		resourcesTableViewer = new TableViewer(composite, SWT.BORDER
				| SWT.FULL_SELECTION);
		table = resourcesTableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		GridData gridDataTable = new GridData(SWT.CENTER, SWT.FILL, true, true);
		table.setLayoutData(gridDataTable);

		final TableColumn newColumnTableColumn1 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn1.setWidth(50);
		newColumnTableColumn1.setText(Messages.getString("AuthorityFilePropertiesPart.sequencenumber"));  //$NON-NLS-1$

		final TableColumn newColumnTableColumn2 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn2.setWidth(90);
		newColumnTableColumn2.setText(Messages.getString("AuthorityFilePropertiesPart.name"));  //$NON-NLS-1$

		final TableColumn newColumnTableColumn4 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn4.setWidth(220);
		newColumnTableColumn4.setText(Messages.getString("AuthorityFilePropertiesPart.value"));  //$NON-NLS-1$

		final TableColumn newColumnTableColumn5 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn5.setWidth(150);
		newColumnTableColumn5.setText(Messages.getString("AuthorityFilePropertiesPart.description"));  //$NON-NLS-1$

		resourcesTableViewer.setContentProvider(new SaturnSWTUtils.SaturnTableViewerDefaultContentProvider());
		resourcesTableViewer.setInput(resources);

		resourcesTableViewer.setLabelProvider(new SaturnSWTUtils.SaturnTableViewerDefaultLabelProvider(){
			public String getColumnText(Object element, int columnIndex) {
				Resource resource = (Resource)element;
				if (columnIndex == 0) {
					return String.valueOf(resource.getId());
				}
				if (columnIndex == 1) {
					return resource.getName();
				}
				if (columnIndex == 2) {
					return resource.getValue();
				}
				if (columnIndex == 3) {
					return resource.getDescritpion();
				}	
				return ""; //$NON-NLS-1$
			}
			});

		modifyParameter();

		GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.FILL;
		gridData2.grabExcessHorizontalSpace = false;
		gridData2.grabExcessVerticalSpace = false;
		gridData2.verticalAlignment = GridData.FILL;
		Composite buttonGroup = new Composite(composite, SWT.NONE);
		buttonGroup.setLayout(new GridLayout());
		buttonGroup.setLayoutData(gridData2);

		GridData gridData3 = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		gridData3.widthHint = 60;

		final Button addButton = new Button(buttonGroup, SWT.NONE);
		addButton.setText(Messages.getString("AuthorityFilePropertiesPart.add"));  //$NON-NLS-1$
		addButton.setLayoutData(gridData3);
		addButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent arg0) {
				doAdd();
			}
		});

		final Button editorButton = new Button(buttonGroup, SWT.NONE);
		editorButton.setText(Messages.getString("AuthorityFilePropertiesPart.edit"));  //$NON-NLS-1$
		editorButton.setLayoutData(gridData3);
		editorButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent arg0) {
				doEdit();
			}
		});

		final Button delButton = new Button(buttonGroup, SWT.NONE);
		delButton.setText(Messages.getString("AuthorityFilePropertiesPart.delete"));  //$NON-NLS-1$
		delButton.setLayoutData(gridData3);
		delButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent arg0) {
				doRemove();
			}
		});
		adaptRecursively(toolkit, composite);

		return composite;
	}

	protected void modifyParameter() {
		// 建立一个表格单元编辑器
		CellEditor[] editors = new CellEditor[5];
		editors[0] = null;
		editors[1] = new TextCellEditor(table);
		editors[3] = new TextCellEditor(table);
		// 设置列属性
		resourcesTableViewer.setColumnProperties(new String[] { "id", "name",   //$NON-NLS-1$ //$NON-NLS-2$
				 "value", "description" });    //$NON-NLS-1$ //$NON-NLS-2$
		// 设置表格单元的编辑器
		resourcesTableViewer.setCellEditors(editors);
		// 设置表格单元的修改器
		AuthorityModel dm = (AuthorityModel) ae.getDACDefinition();
		resourcesTableViewer.setCellModifier(new TableViewerCellModifier(resourcesTableViewer, dm));
	}

	protected String getSectionDescription() {
		return Messages.getString("AuthorityFilePropertiesPart.sourcedeploy");  //$NON-NLS-1$
	}

	protected String getSectionTitle() {
		return Messages.getString("AuthorityFilePropertiesPart.validatedeploy");  //$NON-NLS-1$
	}

	private void setTableValue(AuthorityModel dm) {
		List<Resource> resources = new ArrayList<Resource>();
		
		List<Resource> list = authorityVO.getResources();
		for (int i = 0; i < list.size(); i++) {
			Node node = (Node) list.get(i);
			int id = Integer.parseInt(node.getAttributes()
					.getNamedItem("id").getNodeValue());  //$NON-NLS-1$
			String name = node.getAttributes().getNamedItem("name")  //$NON-NLS-1$
					.getNodeValue();
			String value = node.getAttributes()
					.getNamedItem("value").getNodeValue();  //$NON-NLS-1$
			String descritpion = node.getAttributes().getNamedItem(
					"description").getNodeValue();  //$NON-NLS-1$
			
			Resource resource = new Resource();
			resource.setId(id);
			resource.setName(name);
			resource.setValue(value);
			resource.setDescritpion(descritpion);
			resources.add(resource);
		}
		resourcesTableViewer.setInput(resources);
	}

	public void setTableAttr(AuthorityModel dm) {
		table.removeAll();
		setTableValue(dm);
	}

	private void doAdd() {
		AuthorityModel dm = ae.getDACDefinition();
		AddResourceDialog addResourceDialog = new AddResourceDialog(null, project);

		if (addResourceDialog.open() == IDialogConstants.OK_ID) {
			int id = dm.getResourceId();
			String name = addResourceDialog.getName();
			String value = addResourceDialog.getValue();
			String description = addResourceDialog.getDescritpion();

			Resource resource = new Resource();
			
			resource.setId(id);
			resource.setName(name);
			resource.setValue(value);
			resource.setDescritpion(description);
			List<Resource> resources = this.authorityVO.getResources();
			resources.add(resource);
			resourcesTableViewer.setInput(resources);
			this.dm.updateResource(resources);
		}
	}

	private void doEdit() {
		EditResourceDialog editResourceDialog = new EditResourceDialog(null, project);
		int selIndex = resourcesTableViewer.getTable().getSelectionIndex();
		if (selIndex == -1) {
			MessageDialog.openInformation(null,	Messages.getString("AuthorityFilePropertiesPart.remend"), Messages.getString("AuthorityFilePropertiesPart.chooseedititem"));   //$NON-NLS-1$ //$NON-NLS-2$
		} else {
			 List<Resource> resources = this.authorityVO.getResources();
			Resource resource = (Resource) resources.get(selIndex);
			editResourceDialog.setName(resource.getName());
			editResourceDialog.setValue(resource.getValue());
			editResourceDialog.setDescritpion(resource.getDescritpion());
			editResourceDialog.open();

			if (EditResourceDialog.i == 1) {
				resource.setName(editResourceDialog.getName());
				resource.setValue(editResourceDialog.getValue());
				resource.setDescritpion(editResourceDialog.getDescritpion());
				
				resources.remove(selIndex);
                resources.add(selIndex, resource);
				dm.updateResource(resources);
				resourcesTableViewer.setInput(resources);
			}
		}	
	}

	private void doRemove() {
		if (table.getSelectionCount() > 0) {
			if (MessageDialog.openConfirm(null, Messages.getString("AuthorityFilePropertiesPart.remend"), Messages.getString("AuthorityFilePropertiesPart.confirmdelete"))) {   //$NON-NLS-1$ //$NON-NLS-2$
	
				List<Resource> resources = this.authorityVO.getResources();
				int item = table.getSelectionIndex();
				resources.remove(item);
				for (int i = item; i < (table.getItemCount() - 1); i++) {
					resources.get(i).setId(i + 1);
				}
				
				this.dm.updateResource(resources);
				resourcesTableViewer.setInput(resources);
			}		
		} else {
			MessageDialog.openInformation(null,	Messages.getString("AuthorityFilePropertiesPart.remend"), Messages.getString("AuthorityFilePropertiesPart.choosedeleteitem"));   //$NON-NLS-1$ //$NON-NLS-2$
		}
	}

}
